<template>
  <div class="devired-single">
    <div class="factory-content" v-loading="loading">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="0">
        <el-row :gutter="20">
          <el-col :span="6" align="left">
            <div class="factory-top">
              <h2>
                <icon-svg name="iconRole" slot="prefix"></icon-svg>
                单一型指标
              </h2>
            </div>
          </el-col>
          <el-col :span="18" align="right">
            <div class="btns">
              <el-button @click="clear">
                <icon-svg name="iconCancel"></icon-svg>
                取消
              </el-button>
              <el-button type="primary" @click="handlePreview">
                <icon-svg name="iconFacEye"></icon-svg>
                预览
              </el-button>
              <el-button type="primary" @click="submit">
                <icon-svg name="iconSave"></icon-svg>
                保存
              </el-button>
            </div>
          </el-col>
        </el-row>
        <div class="factory-content-wrapper tag-scrollbar">
          <!-- 逻辑组合 -->
          <div class="section-title">
            <i :class="showLogic ? 'el-icon-caret-bottom' : 'el-icon-caret-right'" @click="showLogic = !showLogic"></i>
            组合逻辑
          </div>
          <el-collapse-transition>
            <div class="section-wrappper" v-if="showLogic">
              <div class="single-selection">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <div class="source-item">
                      <div class="star"></div>
                      <div class="source-title linear-purpose">加工表</div>
                      <div class="source-content">
                        <el-form-item prop="procTable">
                          <el-select v-model="editForm.procTable" filterable clearable>
                            <el-option label="---" value=""></el-option>
                            <el-option
                              v-for="item in tableList"
                              :key="item.tableNm"
                              :label="item.tableNm"
                              :value="item.tableNm"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="source-item">
                      <div class="star"></div>
                      <div class="source-title linear-purpose">加工字段</div>
                      <div class="source-content">
                        <el-form-item prop="procField">
                          <el-select v-model="editForm.procField" filterable clearable>
                            <el-option label="---" value=""></el-option>
                            <el-option
                              v-for="item in fieldList"
                              :key="item.fieldNm"
                              :label="item.fieldNm"
                              :value="item.fieldNm"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="source-item">
                      <div class="star"></div>
                      <div class="source-title linear-purpose">统计方式</div>
                      <div class="source-content">
                        <el-form-item prop="statType">
                          <el-select v-model="editForm.statType" filterable clearable>
                            <el-option label="---" value=""></el-option>
                            <el-option
                              v-for="item in statypeList"
                              :key="item.typeId"
                              :label="item.typeName"
                              :value="item.typeId"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
              <single-field-selector
                :fieldList="fieldList"
                :labs="editForm.labs"
                formProp="labs"
                @addFilter="addFilter"
              >
              </single-field-selector>
            </div>
          </el-collapse-transition>

          <div class="section-title">
            <i
              :class="showResult ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"
              @click="showResult = !showResult"
            ></i>
            结果预览
          </div>
          <el-collapse-transition>
            <div class="section-wrappper" v-if="showResult">
              <devired-result :previewResults="editForm.previewResults"></devired-result>
            </div>
          </el-collapse-transition>
        </div>
      </el-form>
    </div>
    <single-drawer ref="singleDrawer" @confirm="handleSave"></single-drawer>
  </div>
</template>

<script>
import singleFieldSelector from './single-field-selector'
import deviredResult from '../../components/devired-result'
import singleDrawer from '../logic/logic-drawer'
import cloneDeep from 'lodash/cloneDeep'
export default {
  components: {
    singleFieldSelector,
    singleDrawer,
    deviredResult
  },
  data() {
    return {
      loading: false,
      tableList: [],
      fieldList: [],
      statypeList: [],
      oldConfig: {},
      editForm: {
        tagId: '',
        groupId: '',
        tagNm: '',
        fieldNm: '',
        tagStory: '',
        valueType: '',
        execFrequency: '',
        execDtList: [],
        execWkList: [],
        execTm: '',
        procTable: '',
        procField: '',
        primaryKey: '',
        statType: '',
        statNm: '',
        rerun: false,
        rerunTime: 1,
        labs: [],
        previewResults: []
      },
      editFormRules: {
        procTable: [{ required: true, message: '加工表不能为空', trigger: 'change' }],
        procField: [{ required: true, message: '加工字段不能为空', trigger: 'change' }],
        statType: [{ required: true, message: '统计方式不能为空', trigger: 'change' }]
      },
      showLogic: true,
      showResult: false
    }
  },
  created() {
    Promise.all([this.getTableList(), this.getStatype()]).then(() => {
      if (this.$route.query.tagId) {
        this.editForm.tagId = this.$route.query.tagId
        this.getDetail()
      }
      if (this.$route.query.groupId) this.editForm.groupId = this.$route.query.groupId
    })
  },
  watch: {
    'editForm.procTable'(val) {
      this.editForm.procField = ''
      this.editForm.labs.forEach(item => {
        item.labTbl = val
        item.labFldMap = ''
      })
      this.getFieldList()
      const tableItem = this.tableList.find(item => item.tableNm === val)
      this.editForm.primaryKey = tableItem.relaField
    },
    'editForm.statType'(val) {
      const statItem = this.statypeList.find(item => item.typeId === val)
      this.editForm.statNm = statItem.typeName
    }
  },
  methods: {
    getTableList() {
      return new Promise((resolve, reject) => {
        this.$ajax({
          url: this.$ajax.setUrl('der/derKpiType/getAllDetailTable'),
          method: 'get',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.tableList = data.data
            resolve()
          } else {
            this.$message.error(data.data || data.msg)
            reject()
          }
        })
      })
    },
    getFieldList() {
      const tableItem = this.tableList.find(item => item.tableNm === this.editForm.procTable)
      this.$ajax({
        url: this.$ajax.setUrl('der/derKpiType/getTableFields'),
        method: 'post',
        data: this.$ajax.setData({
          dbName: tableItem.dbName,
          plfmId: tableItem.plfmId,
          relaField: tableItem.relaField,
          tableNm: tableItem.tableNm,
          tableType: tableItem.tableType
        })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.fieldList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getStatype() {
      return new Promise((resolve, reject) => {
        this.$ajax({
          url: this.$ajax.setUrl('der/derKpiType/getStaTypeList'),
          method: 'get',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.statypeList = data.data
            resolve()
          } else {
            this.$message.error(data.data || data.msg)
            reject()
          }
        })
      })
    },
    getDetail() {
      this.$ajax({
        url: this.$ajax.setUrl(`der/derKpiType/getSingleKpi/${this.editForm.tagId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          const config = JSON.parse(data.data.configJson)
          this.editForm.tagNm = data.data.tagNm
          this.editForm.fieldNm = data.data.fieldNm
          this.editForm.tagStory = data.data.tagStory
          this.editForm.valueType = data.data.valueType
          this.editForm.rerun = !!data.data.rerun
          this.editForm.rerunTime = data.data.rerunTime || 1
          this.editForm.execFrequency = data.data.execFrequency
          this.editForm.execDtList = data.data.execDtList
          this.editForm.execWkList = data.data.execWkList
          this.editForm.execTm = data.data.execTm
          this.editForm.primaryKey = config.primaryKey
          this.editForm.previewResults = JSON.parse(data.data.previewResults)
          this.showLogic = false
          this.showResult = true
          this.$nextTick(() => {
            this.editForm.procTable = config.procTable
            this.editForm.statType = config.statType
            this.editForm.statNm = config.statNm
            this.$nextTick(() => {
              this.editForm.procField = config.procField
              this.editForm.labs = config.labs
              this.oldConfig = cloneDeep(this.editForm)
            })
          })
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    addFilter() {
      this.editForm.labs.push({
        labTbl: this.editForm.procTable,
        operationType: '',
        oprator: '',
        datTyp: '',
        valueType: '',
        labFldMap: '',
        operationValue: '',
        val: '',
        valLft: '',
        valRit: '',
        valArray: []
      })
    },
    initLabs() {
      this.editForm.labs.forEach(item => {
        item.oprator = item.operationType
        if (item.valueType == '1') {
          item.val = ''
          item.valLft = ''
          item.valRit = ''
          item.valArray = item.operationValue
        } else if (item.valueType == '4' || item.valueType == '5' || item.valueType == '6' || item.valueType == '7') {
          if (item.oprator == 'a<=x<b') {
            item.val = ''
            item.valLft = item.operationValue[0]
            item.valRit = item.operationValue[1]
            item.valArray = []
          } else {
            item.val = item.operationValue
            item.valLft = ''
            item.valRit = ''
            item.valArray = []
          }
        } else {
          item.val = item.operationValue
          item.valLft = ''
          item.valRit = ''
          item.valArray = []
        }
      })
    },
    handlePreview() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.initLabs()
          let params = {
            procTable: this.editForm.procTable,
            procField: this.editForm.procField,
            primaryKey: this.editForm.primaryKey,
            statType: this.editForm.statType,
            labs: this.editForm.labs
          }
          this.loading = true
          this.$ajax({
            url: this.$ajax.setUrl('der/derKpiType/previewSingleResult'),
            method: 'post',
            data: this.$ajax.setData({
              configJson: JSON.stringify(params)
            })
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.$message.success(data.msg)
              this.editForm.previewResults = data.data
              this.oldConfig = cloneDeep(this.editForm)
              this.showLogic = false
              this.showResult = true
            } else {
              this.$message.error(data.data || data.msg)
            }
            this.loading = false
          })
        }
      })
    },
    clear() {
      this.$confirm('确定取消最新的编辑？').then(() => {
        const config = cloneDeep(this.oldConfig)
        if (config.tagId) {
          this.editForm.tagNm = config.tagNm
          this.editForm.fieldNm = config.fieldNm
          this.editForm.tagStory = config.tagStory
          this.editForm.valueType = config.valueType
          this.editForm.execFrequency = config.execFrequency
          this.editForm.execDtList = config.execDtList
          this.editForm.execWkList = config.execWkList
          this.editForm.execTm = config.execTm
          this.editForm.primaryKey = config.primaryKey
          this.editForm.previewResults = config.previewResults
          this.editForm.rerun = config.rerun
          this.editForm.rerunTime = config.rerunTime
          this.$nextTick(() => {
            this.editForm.procTable = config.procTable
            this.editForm.statType = config.statType
            this.editForm.statNm = config.statNm
            this.$nextTick(() => {
              this.editForm.procField = config.procField
              this.editForm.labs = config.labs
            })
          })
        } else {
          this.editForm.tagNm = ''
          this.editForm.fieldNm = ''
          this.editForm.tagStory = ''
          this.editForm.valueType = ''
          this.editForm.execFrequency = ''
          this.editForm.execDtList = []
          this.editForm.execWkList = []
          this.editForm.execTm = ''
          this.editForm.primaryKey = ''
          this.editForm.procTable = ''
          this.editForm.statType = ''
          this.editForm.statNm = ''
          this.editForm.procField = ''
          this.editForm.labs = []
          this.editForm.previewResults = []
          this.editForm.rerun = false
          this.editForm.rerunTime = 1
        }
        this.$forceUpdate()
      })
    },
    submit() {
      if (!this.$utils.compareObject(this.oldConfig, this.editForm)) {
        this.$message.info('逻辑配置有变化，请先预览再保存！')
        return
      }
      this.$refs.editForm.validate(valid => {
        if (valid) {
          let params = {
            tagId: this.editForm.tagId,
            tagNm: this.editForm.tagNm,
            fieldNm: this.editForm.fieldNm,
            tagStory: this.editForm.tagStory,
            valueType: this.editForm.valueType,
            rerun: this.editForm.rerun,
            rerunTime: this.editForm.rerunTime,
            execFrequency: this.editForm.execFrequency,
            execDtList: this.editForm.execDtList,
            execWkList: this.editForm.execWkList,
            execTm: this.editForm.execTm
          }
          this.$refs.singleDrawer.showDrawer(params)
        }
      })
    },
    handleSave(params) {
      this.editForm.execFrequency = params.execFrequency
      this.editForm.execDtList = params.execDtList
      this.editForm.execWkList = params.execWkList
      this.editForm.execTm = params.execTm
      this.editForm.fieldNm = params.fieldNm
      this.editForm.tagNm = params.tagNm
      this.editForm.tagStory = params.tagStory
      this.editForm.valueType = params.valueType
      this.editForm.rerun = params.rerun
      this.editForm.rerunTime = params.rerunTime
      let configParams = {
        procTable: this.editForm.procTable,
        procField: this.editForm.procField,
        primaryKey: this.editForm.primaryKey,
        statType: this.editForm.statType,
        statNm: this.editForm.statNm,
        labs: this.editForm.labs
      }
      let config = {
        configJson: JSON.stringify(configParams),
        execFrequency: params.execFrequency,
        execDtList: params.execDtList,
        execWkList: params.execWkList,
        execTm: params.execTm,
        fieldNm: params.fieldNm,
        previewResults: JSON.stringify(this.editForm.previewResults),
        tagNm: params.tagNm,
        tagStory: params.tagStory,
        valueType: params.valueType,
        rerun: params.rerun,
        rerunTime: params.rerunTime
      }
      if (this.editForm.tagId) config.tagId = this.editForm.tagId
      if (this.editForm.groupId) config.groupId = this.editForm.groupId
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl('der/derKpiType/saveSingleKpi'),
        method: 'post',
        data: this.$ajax.setData(config)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (!this.editForm.tagId) this.editForm.tagId = data.data
          this.$message.success(data.msg)
          this.$refs.singleDrawer.beforeClose()
          this.oldConfig = cloneDeep(this.editForm)
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss">
.devired-single {
  position: absolute;
  top: 60px;
  right: 0;
  bottom: 5px;
  left: 0;
  .factory-content {
    margin-left: 0;
    margin-right: 0;
    padding: 0 20px;
  }
  .factory-top {
    line-height: 50px;
    color: $theme-color;
    svg {
      margin-right: 10px;
    }
  }
  .btns {
    text-align: right;
    .el-button {
      margin-top: 9px;
    }
    .el-button {
      font-size: 15px;
      color: #455fbc;
      background-color: transparent;
      border-color: transparent;
      svg {
        font-size: 20px;
        width: 20px;
        height: 20px;
        margin-right: 3px;
        margin-top: -5px;
        vertical-align: middle;
        // color: #455fbc;
      }
      & + .el-button {
        margin-left: 0;
      }
      &.disabled {
        color: #999;
      }
    }
    .el-input--prefix {
      .el-input__inner {
        height: 35px;
        color: #455fbc;
        border-color: #455fbc;
      }
      .el-input__icon {
        color: #455fbc;
      }
      .el-input__prefix,
      .el-input__suffix {
        top: -3px;
      }
    }
  }
  .section-title {
    font-size: 18px;
    font-weight: bold;
    height: 80px;
    padding: 20px;
    line-height: 40px;
    color: #1e3592;
    background-color: #c0d2f6;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    & + .section-title {
      margin-top: 10px;
    }
    i {
      cursor: pointer;
    }
    span {
      font-size: 14px;
      font-weight: normal;
      color: #4a5593;
      margin-left: 10px;
    }
  }
  .section-wrappper {
    border: 1px solid #e4e7ed;
    padding: 10px;
    margin-bottom: 10px;
  }
  .single-selection {
    width: 100%;
    overflow: hidden;
  }
  .source-item {
    width: 100%;
    height: 45px;
    margin-bottom: 20px;
    box-shadow: #eee 0 0 10px;
    position: relative;
    .source-title {
      font-weight: bold;
      width: 150px;
      padding-left: 50px;
      line-height: 45px;
      color: #fff;
      position: absolute;
      &:before {
        width: 10px;
        height: 10px;
        content: '';
        background-color: #eee9ff;
        border: 2px solid #cfc7ee;
        margin-top: -5px;
        position: absolute;
        top: 50%;
        left: 20px;
        border-radius: 50%;
      }
      &:after {
        width: 0;
        height: 0;
        content: '';
        margin-top: -10px;
        border-top: 10px solid transparent;
        border-bottom: 10px solid transparent;
        position: absolute;
        top: 50%;
        right: -10px;
      }
      &.linear-purpose:after {
        border-left: 10px solid #7c6bed;
      }
      &.linear-blue:after {
        border-left: 10px solid #635fd7;
      }
      &.linear-cyan:after {
        border-left: 10px solid #0696ec;
      }
      &.linear-red:after {
        border-left: 10px solid #c563ee;
      }
    }
    .source-content {
      line-height: 45px;
      padding: 0 30px 0 180px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      &.rela-content {
        padding-left: 195px;
      }
    }
    .el-select {
      width: 100%;
    }
    .el-select .el-input__inner,
    .el-input .el-input__inner {
      height: 45px;
      line-height: 45px;
      border: 0;
      background-color: transparent;
    }
  }
}
</style>
